
package com.epam.android.training.app.services;

import com.epam.android.training.app.db.TestsDb;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Service for updates new tests
 * 
 * @author Natallia_Kukharchyk
 */
public class TestService extends Service {

  private static final long UPDATE_INTERVAL = 2 * 60 * 1000;

  private static final long DELAY_INTERVAL = 2 * 60 * 1000;

  private static final String TAG = "service";

  private static final String EXCEPTION_MSG = "TestService InterruptedException";

  private static final String NEW_TEST_TITLE = "newTestTitle";

  private static final int NEW_TESTS_QUANTITIES = 1;

  private static final int NEW_QUESTIONS_QUANTITIES = 5;

  private static final int NEW_ANSWERS_QUANTITIES = 7;

  private final Timer timer = new Timer();

  private TestsDb db;

  @Override
  public IBinder onBind(Intent arg0) {
    return null;
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    timer.cancel();
  }

  @Override
  public void onStart(Intent intent, int startid) {
    startTestService();

  }

  private void startTestService() {
    timer.scheduleAtFixedRate(

    new TimerTask() {

      @Override
      public void run() {
        doServiceWork();
        try {
          Thread.sleep(UPDATE_INTERVAL);
        } catch (InterruptedException e) {
          Log.e(TAG, EXCEPTION_MSG + e.getLocalizedMessage());
        }
      }
    }, DELAY_INTERVAL, UPDATE_INTERVAL);
  }

  /**
   * add new tests (for this case - it simply generate some data the same as
   * default tests)
   * 
   * @param context
   */
  private void insertNewTests(Context context) {
    db = new TestsDb(context);
    db.insertTest(NEW_TESTS_QUANTITIES, NEW_QUESTIONS_QUANTITIES, NEW_ANSWERS_QUANTITIES,
        NEW_TEST_TITLE + new Random().nextInt(123));
  }

  private void doServiceWork() {
    insertNewTests(getApplicationContext());
    Intent i = new Intent();
    i.setAction("com.epam.android.taining.app.TEST_INTENT_RECEIVER");
    getApplicationContext().sendBroadcast(i);
  }
}
